package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.Config;
import com.qianniu.napi.admin.entity.Merchant;
import com.qianniu.napi.admin.entity.User;
import com.qianniu.napi.admin.entity.UserRole;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 商家
 * </p>
 *
 * @author chenxuebin
 * @since 2018-06-17
 */
@Controller
public class MerchantController {

    private static final Logger logger = LoggerFactory.getLogger(MerchantController.class);

    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IUserRoleService userRoleService;

    //    @RequiresPermissions("admin:user:view")
    @RequestMapping("admin/merchant/index")
    public String index(Model model) {

        Wrapper<Config> wrapper = new EntityWrapper<Config>();
        wrapper.where(" type={0} and pid is null ", "business_category").orderBy("id", true);
        List<Config> list = configService.selectList(wrapper);
        model.addAttribute("list", list);
        model.addAttribute("pwd", "");
        model.addAttribute("idu", "");
        model.addAttribute("isAdmin", ObjectUtil.getIsAdmin());
        logger.info(">>>admin/merchant/index return");

        return "admin/merchant";
    }

    //    @RequiresPermissions("admin:user:view")
    @RequestMapping("/admin/merchant/list")
    @ResponseBody
    public Page<Merchant> alist(@RequestParam(value = "offset", required = false) Integer offset,
                                @RequestParam(value = "status", required = false) Integer status,
                                @RequestParam(value = "search", required = false) String search,
                                @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<Merchant> wrapper = new EntityWrapper<Merchant>();
        if (ObjectUtil.getUserType() != 99) wrapper.eq("id", ObjectUtil.getMid());
        wrapper.eq("state", 1);
//        if (status != 99) wrapper.eq("xftype", status);
        logger.info("==========");
        logger.info("==========uid=" + ObjectUtil.getUid());
        logger.info("==========mid=" + ObjectUtil.getMid());
        logger.info("==========mpid=" + ObjectUtil.getMpid());
        logger.info("==========sid=" + ObjectUtil.getSid());

        if (!Strings.isNullOrEmpty(search))
            wrapper.andNew().eq("name", search).or().eq("mcode", search);

        wrapper.orderBy("id", true);
        Page<Merchant> page = merchantService.selectPage(new Page<Merchant>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/merchant/add")
    public String add(@Valid Merchant bean, BindingResult bindingResult, Model model) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setUid(ObjectUtil.getUid());
        bean.insert();

        // 创建商家用户和密码
        User muser = new User();
        muser.setUsername(bean.getMcode());
//        muser.setIsMch(1);
//        muser.setIsPlatform(1);
        muser.setIsAdmin(1);
        muser.setCreatetime(new Date());
        muser.setState(1);
        muser.setMid(bean.getId());
        muser.setUserType(39);// 默认商家专业版
        muser.setPhoto(bean.getPic());
        muser.setGuid(StringUtil.getGUID());
        String pwd = bean.getMcode() + "#ncd";

        muser.setSalt(muser.getGuid().substring(0, 24));
        muser.setPassword(ObjectUtil.getPwd(pwd, muser.getSalt(), 3));

        muser.insert();
        String rkey = Constants.REDIS_MUSER_ + ObjectUtil.getUid();
        redisService.set(rkey, muser);

        // 创建用户角色
        UserRole userrole = new UserRole();
        userrole.setUserid(muser.getId());
        userrole.setRoleid(1l);// 默认1
        userrole.setState(1);// 默认1
        userrole.setMid(bean.getId());// 默认1
        userrole.setUid(muser.getId());// 默认1
        userrole.insert();

        model.addAttribute("pwd", pwd);
        model.addAttribute("idu", bean.getMcode());
        model.addAttribute("isAdmin", ObjectUtil.getIsAdmin());

        logger.info(">>>admin/merchant/add return");

        return "admin/merchant";
    }

    @RequestMapping("/admin/merchant/getMerchantById")
    @ResponseBody
    public Merchant getMerchantById(long id) {
        Merchant merchant = merchantService.selectById(id);
        return merchant;
    }

    @RequestMapping("/admin/merchant/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        logger.info("==========mcode=" + ObjectUtil.getMcode());

        Merchant merchant = merchantService.selectById(id);
        User user = userService.selectOne(new EntityWrapper<User>().eq("username", merchant.getMcode()));
        userRoleService.delete(new EntityWrapper<UserRole>().eq("userid", user.getId()));
        user.deleteById();
        merchant.deleteById();

        return 1;
    }

    @RequestMapping("/admin/merchant/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        Merchant bean = new Merchant();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        merchantService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/merchant/resetpwd")
    @ResponseBody
    public String resetpwd(long id) {

        Merchant merchant = merchantService.selectById(id);
        User muser = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,username,password,salt").eq("username", merchant.getMcode()));

        muser.setSalt(StringUtil.getGUID().substring(0, 24));
        String pwd = merchant.getMcode() + "#" + ObjectUtil.randomStrings(6, 1).get(0);
        muser.setPassword(ObjectUtil.getPwd(pwd, muser.getSalt(), 3));
        muser.updateById();

        return pwd;
    }

    @RequestMapping("/admin/merchant/modify")
    public String update(Merchant bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        boolean isSuccc = merchantService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

}
